package com.warom.sdg.repository;

import android.content.Context;
import android.util.Log;

import com.warom.sdg.dao.PlcDeviceDao;
import com.warom.sdg.database.SdgDatabase;
import com.warom.sdg.model.PlcDeviceEntity;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Consumer;
import java.util.ArrayList;

/**
 * PLC设备仓库类
 * 提供设备数据库操作的高级接口，管理PlcDeviceDao实例
 */
public class PlcDeviceRepository {
    private static final String TAG = "PlcDeviceRepository";
    
    // 数据库和DAO
    private final SdgDatabase database;
    private final PlcDeviceDao plcDeviceDao;
    
    // 线程池执行器，用于异步操作
    private final ExecutorService executor;
    
    /**
     * 构造函数
     * @param context 上下文
     */
    public PlcDeviceRepository(Context context) {
        database = SdgDatabase.getInstance(context);
        plcDeviceDao = database.getPlcDeviceDao();
        executor = Executors.newFixedThreadPool(2); // 创建线程池
    }
    
    /**
     * 插入设备记录
     * @param device 设备实体
     * @param successCallback 成功回调，返回新插入的ID
     * @param errorCallback 错误回调，返回错误信息
     */
    public void insert(final PlcDeviceEntity device, Consumer<Long> successCallback, Consumer<String> errorCallback) {
        Log.d(TAG, "插入设备: " + device.toString());
        executor.execute(() -> {
            try {
                long id = plcDeviceDao.insert(device);
                Log.d(TAG, "设备插入成功，ID: " + id);
                if (successCallback != null) {
                    successCallback.accept(id);
                }
            } catch (Exception e) {
                String errorMsg = "设备插入失败: " + e.getMessage();
                Log.e(TAG, errorMsg, e);
                if (errorCallback != null) {
                    errorCallback.accept(errorMsg);
                }
            }
        });
    }
    
    /**
     * 更新设备信息
     * @param device 设备实体
     * @param onComplete 操作完成回调
     * @param onError 错误回调
     */
    public void update(final PlcDeviceEntity device, Runnable onComplete, Consumer<String> onError) {
        Log.d(TAG, "更新设备: " + device.toString());
        executor.execute(() -> {
            try {
                plcDeviceDao.update(device);
                Log.d(TAG, "设备更新成功，ID: " + device.getDeviceId());
                if (onComplete != null) {
                    onComplete.run();
                }
            } catch (Exception e) {
                String errorMsg = "设备更新失败: " + e.getMessage();
                Log.e(TAG, errorMsg, e);
                if (onError != null) {
                    onError.accept(errorMsg);
                }
            }
        });
    }
    
    /**
     * 删除设备
     * @param device 设备实体
     * @param onComplete 操作完成回调
     * @param onError 错误回调
     */
    public void delete(final PlcDeviceEntity device, Runnable onComplete, Consumer<String> onError) {
        Log.d(TAG, "删除设备: " + device.toString());
        executor.execute(() -> {
            try {
                plcDeviceDao.delete(device);
                Log.d(TAG, "设备删除成功，ID: " + device.getDeviceId());
                if (onComplete != null) {
                    onComplete.run();
                }
            } catch (Exception e) {
                String errorMsg = "设备删除失败: " + e.getMessage();
                Log.e(TAG, errorMsg, e);
                if (onError != null) {
                    onError.accept(errorMsg);
                }
            }
        });
    }
    
    /**
     * 获取所有设备
     * @param successCallback 成功回调，返回设备列表
     * @param errorCallback 错误回调，返回错误信息
     */
    public void getAllDevices(Consumer<List<PlcDeviceEntity>> successCallback, Consumer<String> errorCallback) {
        executor.execute(() -> {
            try {
                List<PlcDeviceEntity> deviceList = plcDeviceDao.getAllDevices();
                if (successCallback != null) {
                    successCallback.accept(deviceList);
                }
            } catch (Exception e) {
                String errorMsg = "获取所有设备失败: " + e.getMessage();
                Log.e(TAG, errorMsg, e);
                if (errorCallback != null) {
                    errorCallback.accept(errorMsg);
                }
            }
        });
    }
    
    /**
     * 获取活跃设备
     * @param successCallback 成功回调，返回设备列表
     * @param errorCallback 错误回调，返回错误信息
     */
    public void getActiveDevices(Consumer<List<PlcDeviceEntity>> successCallback, Consumer<String> errorCallback) {
        executor.execute(() -> {
            try {
                List<PlcDeviceEntity> deviceList = plcDeviceDao.getActiveDevices();
                if (successCallback != null) {
                    successCallback.accept(deviceList);
                }
            } catch (Exception e) {
                String errorMsg = "获取活跃设备失败: " + e.getMessage();
                Log.e(TAG, errorMsg, e);
                if (errorCallback != null) {
                    errorCallback.accept(errorMsg);
                }
            }
        });
    }
    
    /**
     * 根据ID获取设备
     * @param deviceId 设备ID
     * @param successCallback 成功回调，返回设备实体
     * @param errorCallback 错误回调，返回错误信息
     */
    public void getDeviceById(final int deviceId, Consumer<PlcDeviceEntity> successCallback, Consumer<String> errorCallback) {
        executor.execute(() -> {
            try {
                PlcDeviceEntity device = plcDeviceDao.getDeviceById(deviceId);
                if (device != null) {
                    if (successCallback != null) {
                        successCallback.accept(device);
                    }
                } else {
                    String errorMsg = "未找到ID为 " + deviceId + " 的设备";
                    Log.e(TAG, errorMsg);
                    if (errorCallback != null) {
                        errorCallback.accept(errorMsg);
                    }
                }
            } catch (Exception e) {
                String errorMsg = "获取设备失败: " + e.getMessage();
                Log.e(TAG, errorMsg, e);
                if (errorCallback != null) {
                    errorCallback.accept(errorMsg);
                }
            }
        });
    }
    
    /**
     * 根据IP地址获取设备
     * @param deviceIp 设备IP地址
     * @param successCallback 成功回调，返回设备实体
     * @param errorCallback 错误回调，返回错误信息
     */
    public void getDeviceByIp(final String deviceIp, Consumer<PlcDeviceEntity> successCallback, Consumer<String> errorCallback) {
        executor.execute(() -> {
            try {
                PlcDeviceEntity device = plcDeviceDao.getDeviceByIp(deviceIp);
                if (device != null) {
                    if (successCallback != null) {
                        successCallback.accept(device);
                    }
                } else {
                    String errorMsg = "未找到IP为 " + deviceIp + " 的设备";
                    Log.e(TAG, errorMsg);
                    if (errorCallback != null) {
                        errorCallback.accept(errorMsg);
                    }
                }
            } catch (Exception e) {
                String errorMsg = "获取设备失败: " + e.getMessage();
                Log.e(TAG, errorMsg, e);
                if (errorCallback != null) {
                    errorCallback.accept(errorMsg);
                }
            }
        });
    }
    
    /**
     * 根据设备类型ID获取设备列表 (异步方法)
     * @param deviceTypeId 设备类型ID
     * @param successCallback 成功回调，返回设备列表
     * @param errorCallback 错误回调，返回错误信息
     */
    public void getDevicesByTypeId(final int deviceTypeId, Consumer<List<PlcDeviceEntity>> successCallback, Consumer<String> errorCallback) {
        executor.execute(() -> {
            try {
                List<PlcDeviceEntity> deviceList = plcDeviceDao.getDevicesByTypeId(deviceTypeId);
                if (successCallback != null) {
                    successCallback.accept(deviceList);
                }
            } catch (Exception e) {
                String errorMsg = "获取设备类型ID为 " + deviceTypeId + " 的设备失败: " + e.getMessage();
                Log.e(TAG, errorMsg, e);
                if (errorCallback != null) {
                    errorCallback.accept(errorMsg);
                }
            }
        });
    }
    
    /**
     * 根据设备类型ID获取设备列表 (同步方法)
     * @param deviceTypeId 设备类型ID
     * @return 设备列表，如果出错则返回空列表
     */
    public List<PlcDeviceEntity> listByDeviceTypeId(final int deviceTypeId) {
        try {
            return plcDeviceDao.getDevicesByTypeId(deviceTypeId);
        } catch (Exception e) {
            String errorMsg = "获取设备类型ID为 " + deviceTypeId + " 的设备失败: " + e.getMessage();
            Log.e(TAG, errorMsg, e);
            return new ArrayList<>();
        }
    }
    
    /**
     * 删除所有设备
     * @param onComplete 操作完成回调
     * @param onError 错误回调
     */
    public void deleteAllDevices(Runnable onComplete, Consumer<String> onError) {
        executor.execute(() -> {
            try {
                plcDeviceDao.deleteAll();
                Log.d(TAG, "已删除所有设备");
                if (onComplete != null) {
                    onComplete.run();
                }
            } catch (Exception e) {
                String errorMsg = "删除所有设备失败: " + e.getMessage();
                Log.e(TAG, errorMsg, e);
                if (onError != null) {
                    onError.accept(errorMsg);
                }
            }
        });
    }
    
    /**
     * 根据ID删除设备
     * @param deviceId 设备ID
     * @param onComplete 操作完成回调
     * @param onError 错误回调
     */
    public void deleteById(final int deviceId, Runnable onComplete, Consumer<String> onError) {
        executor.execute(() -> {
            try {
                // 先获取设备
                PlcDeviceEntity device = plcDeviceDao.getDeviceById(deviceId);
                if (device != null) {
                    plcDeviceDao.delete(device);
                    Log.d(TAG, "设备删除成功，ID: " + deviceId);
                    if (onComplete != null) {
                        onComplete.run();
                    }
                } else {
                    String errorMsg = "删除失败: 未找到ID为 " + deviceId + " 的设备";
                    Log.e(TAG, errorMsg);
                    if (onError != null) {
                        onError.accept(errorMsg);
                    }
                }
            } catch (Exception e) {
                String errorMsg = "根据ID删除设备失败: " + e.getMessage();
                Log.e(TAG, errorMsg, e);
                if (onError != null) {
                    onError.accept(errorMsg);
                }
            }
        });
    }
} 